package com.ly.common.core.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.ly.common.core.config.properties.AliyunSmsProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 短信工具类
 * @author luoyun
 * @Date: 2025/6/29 16:12
 * @Note:
 */
@Slf4j
public class SmsUtils {

    private static final int MAX_MESSAGE_PER_MINUTE = 5;
    private static final int MILLIS_PER_MINUTE = 60000;
    private static final int MAX_TOTAL_MESSAGE_PER_MINUTE = 20;
    private static ConcurrentHashMap<String, Long> ipLastRequestTime = new ConcurrentHashMap();
    private static ConcurrentHashMap<String, Integer> ipRequestCount = new ConcurrentHashMap();
    private static ConcurrentHashMap<String, Boolean> ipBlacklist = new ConcurrentHashMap();

    private static IAcsClient acsClient;
    private static AliyunSmsProperties smsProperties;

    public SmsUtils() {
        smsProperties = SpringUtils.getBean(AliyunSmsProperties.class);
        // 初始化阿里云客户端
        String regionId = smsProperties.getRegionId();
        String accessKeyId = smsProperties.getAccessKeyId();
        String accessKeySecret = smsProperties.getAccessKeySecret();
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        // DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        this.acsClient = new DefaultAcsClient(profile);
    }

    /**
     * 发送短信
     * @param phoneNumbers 手机号（多个用逗号分隔）
     * @param templateParam 短信模板参数（如 {"code": "123456"}）
     * @return 是否发送成功
     */
    public static boolean sendSms(String phoneNumbers, String templateParam) {
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phoneNumbers); // 手机号
        request.setSignName(smsProperties.getSignName());         // 短信签名
        request.setTemplateCode(smsProperties.getTemplateCode()); // 短信模板 CODE
        request.setTemplateParam(templateParam); // 模板参数（JSON 字符串）

        try {
            SendSmsResponse response = acsClient.getAcsResponse(request);
            return "OK".equals(response.getCode()); // 发送成功返回 "OK"
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送短信-模拟
     * @return
     */
    public static boolean sendSms() {
        return true;
    }

    /**
     * 短信限流-验证当前短信发送数量
     * @param ip
     * @return
     */
    public static boolean canSendSms(String ip) {
        long currentTime = System.currentTimeMillis();
        long lastRequestTime = (Long)ipLastRequestTime.getOrDefault(ip, 0L);
        int requestCount = (Integer)ipRequestCount.getOrDefault(ip, 0);
        log.info("IP：{}, Msg requestCount：{} ", ip, requestCount);
        if ((Boolean)ipBlacklist.getOrDefault(ip, false)) {
            log.error("IP：{}, 进入黑名单，禁止发送请求短信！", ip);
            return false;
        } else if (currentTime - lastRequestTime >= 60000L) {
            ipRequestCount.put(ip, 1);
            ipLastRequestTime.put(ip, currentTime);
            return true;
        } else {
            ipRequestCount.put(ip, requestCount + 1);
            if (requestCount < 5) {
                return true;
            } else if (requestCount >= 20) {
                ipBlacklist.put(ip, true);
                return false;
            } else {
                log.error("IP：{}, 1分钟内请求短信超过5次，请稍后重试！", ip);
                return false;
            }
        }
    }

    public static void clearSendSmsCount(String ip) {
        long currentTime = System.currentTimeMillis();
        ipRequestCount.put(ip, 0);
        ipLastRequestTime.put(ip, currentTime);
    }
}
